package com.steven.nio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Elevetor {
	public static void main(String[] args) throws UnknownHostException,
			IOException {
		Socket socket = new Socket("192.168.218.15", 502);

		InputStream is = socket.getInputStream();

		OutputStream os = socket.getOutputStream();

		// 中心主机需要查询6号分机的数据
		// A5-81-06-00-00-87-5A
		// 1010 0101 1000 0001
		String[] hexString = new String[] { "0x0A", "0x81", "0x06", "0x00", "0x00", "0x87",
				"0x5A" };
		byte[] sendInfo = new byte[] { 0x0A, 0x5, 0x8, 0x1, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x8, 0x7, 0x5, 0xA }; // 发送给Modbus Slave软件的消息
		/*List<Byte> byteList = new ArrayList<Byte>();
		for (String hex : hexString) {
			byte[] bytes = hexStringToBytes(hex);
			for (byte b : bytes) {
				byteList.add(b);
			}
		}
		byte[] sendInfo = new byte[byteList.size()];
		for (int i = 0; i < byteList.size(); i++) {
			sendInfo[i] = byteList.get(i);
		}*/
		/*
		 * byte[] sendInfo = new byte[] { , 0x07, 0x00, 0x00, 0x00, 0x06, 0x01,
		 * 0x03, 0x00, 0x00, 0x00, 0x08 }; // 发送给Modbus Slave软件的消息
		 */

		os.write(sendInfo);

		os.flush();

		byte[] bs = new byte[32];

		int i = is.read(bs);
		if (i < 9) {
			if (i == 0) {
				System.out.println("unexpected close of connection at remote end");

			} else {
				System.out.println("response was too short - " + i + " chars");
			}
		} else if (0 != (bs[7] & 0x80)) {
			System.out.println("Modbus exception response - type " + bs[8]);
		}/*
		 * else if (i != (9+2*num_regs)) {
		 * 
		 * System.out.println("incorrect response size is "+i+" expected "+(9+2*
		 * num_regs));
		 * 
		 * }
		 */else {

			/*
			 * for (i=0;i<num_regs;i++) {
			 * 
			 * int w = (bs[9+i+i]<<8) + bs[10+i+i];
			 * 
			 * System.out.println("word "+i+" = "+w);
			 * 
			 * }
			 */

		}

		// close down

		socket.close();

		/*
		 * } catch (Exception e) {
		 * 
		 * System.out.println("exception :"+e);
		 * 
		 * }
		 */

	}

	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
}
